<html>

<head>
        <!-- import ONNXRuntime Web from CDN -->
        <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
</head>

<body>
    <h1>Example</h1>
    <div>
        <input title= "Image from File" type="file" id="file-in" name="file-in">
    </div>
    <h3>Image from file</h3>
    <div>
        <img id="original-image" src="#" />
    </div>
    <h3>Image from tensor</h3>
    <canvas id="canvasHTMLElement"></canvas>
    <h3>Image from tensor resized</h3>
    <canvas id="canvasHTMLElementResize"></canvas>
    <h3>Image from tensor (ImageData)</h3>
    <canvas id="canvasImageData"></canvas>

</body>
<script>
    var canvasHTML = document.getElementById('canvasHTMLElement');
    var canvasResize = document.getElementById('canvasHTMLElementResize');
    var canvasImageData = document.getElementById('canvasImageData');

    async function handleImage(img) {

    // HTML Element --> Tensor
      const htmlTensor = await ort.Tensor.fromImage(img);
    // HTML Element --> Tensor + resized
      const resizedTensor = await ort.Tensor.fromImage(img, options = {resizedWidth: 224, resizedHeight: 224});
    // Tensor --> ImageData
      const imageHTML = htmlTensor.toImageData();
    // Tensor --> ImageData (resized)
      const resizeImage = resizedTensor.toImageData();
    // ImageData --> Tensor
      const imageDataTensor = await ort.Tensor.fromImage(imageHTML);
      const imageImageData = imageDataTensor.toImageData();
    
    // Presenting the images on dom
      canvasHTML.width = imageHTML.width;
      canvasHTML.height = imageHTML.height;
      let context = canvasHTML.getContext('2d');
      context.putImageData(imageHTML, 0, 0);

      canvasResize.width = resizeImage.width;
      canvasResize.height = resizeImage.height;
      context = canvasResize.getContext('2d');
      context.putImageData(resizeImage, 0, 0);

      canvasImageData.width = imageImageData.width;
      canvasImageData.height = imageImageData.height;
      context = canvasImageData.getContext('2d');
      context.putImageData(imageImageData, 0, 0);
    }

    function loadImage(fileReader) {
      var img = document.getElementById("original-image");
      img.onload = () => handleImage(img);
      img.src = fileReader.result;
    }

    function main() {
      document.getElementById("file-in").onchange = function (evt) {
          let target = evt.target || window.event.src, files = target.files;
          if (FileReader && files && files.length) {
              var fileReader = new FileReader();
              fileReader.onload = () => loadImage(fileReader);
              fileReader.readAsDataURL(files[0]);
          }
      };
    }

    main();

</script>

</html>
